//
//  TXTDownloader.m
//  FileSharing
//
//  Created by 祁俊喜 on 2024/4/23.
//

#import "TXTDownloader.h"

@interface TXTDownloader ()<NSURLConnectionDataDelegate>

@property (nonatomic, strong) NSURLConnection *cnnt;

@property (nonatomic, strong) NSFileHandle *writeHandle;

@property (nonatomic, assign) long long currentLength;

@property (nonatomic, assign) long long sumLength;

@end

@implementation TXTDownloader

-(void)start {
    _downloading = YES;
    NSURL *url = [NSURL URLWithString:self.txtUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSString *value = [NSString stringWithFormat:@"bytes=%lld-",self.currentLength];
    [request setValue:value forHTTPHeaderField:@"Range"];
    [request setValue:@"" forHTTPHeaderField:@"Accept-Encoding"];
    self.cnnt = [NSURLConnection connectionWithRequest:request delegate:self];
}

-(void)pause {
    _downloading = NO;
    [self.cnnt cancel];
    self.cnnt = nil;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response {
    if(self.sumLength) return;
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [caches stringByAppendingPathComponent:@"sharing"];
    filePath = [filePath stringByAppendingPathComponent:[self.txtUrl lastPathComponent]];
    filePath = [filePath stringByRemovingPercentEncoding];
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr createFileAtPath:filePath contents:nil attributes:nil];
    self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    self.sumLength = response.expectedContentLength;
    NSLog(@"总长度：%lld",self.sumLength);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    self.currentLength += data.length;
    double progress = (double)self.currentLength;
    if (self.progressHandler) {
        self.progressHandler(progress);
    }
    [self.writeHandle seekToEndOfFile];
    [self.writeHandle writeData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [self.writeHandle closeFile];
    self.currentLength = 0;
    self.sumLength = 0;
    if (self.completionHandler) {
        self.completionHandler();
    }
}


@end
